package com.zheng.redpacket.server.controller.redis;

import com.zheng.redpacket.api.CommonResult;
import com.zheng.redpacket.api.ResultCode;
import com.zheng.redpacket.server.dto.RedPacketDto;
import com.zheng.redpacket.server.serivce.RedPacketService;
import com.zheng.redpacket.server.serivce.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;

@RestController
@RequestMapping("/packet")
public class RedPacketController {
    private static final Logger LOGGER = LoggerFactory.getLogger(RedPacketController.class);

    @Autowired
    private RedPacketService redPacketService;
    @Autowired
    private RedisService redisService;

    @PostMapping("/handout")
    public CommonResult handOut(@Validated @RequestBody RedPacketDto dto, BindingResult result) {
        if (result.hasErrors()) {
            return new CommonResult(ResultCode.VALIDATE_FAILED);
        }
        try {
            String redId = redPacketService.handOut(dto);
            return CommonResult.success(redId);
        } catch (Exception e) {
            LOGGER.error("发送红包异常：dto = {}", dto, e.fillInStackTrace());
            return CommonResult.failed();
        }
    }

    @GetMapping("/rob")
    public CommonResult robRedPackets(@RequestParam Integer userId, @RequestParam String redId) {
        try {
            BigDecimal result = redPacketService.rod(userId, redId);
            if (result != null) {
                return CommonResult.success(result);
            }else {
                return CommonResult.failed("红包已经抢完了");
            }
        } catch (Exception e) {
            LOGGER.error("抢红包发生异常：userId={}, redId={}", userId, redId, e.fillInStackTrace());
        }
        return CommonResult.failed();
    }

}
